import 'dart:math';

import 'package:expandable/expandable.dart';
import 'package:expansion_tile_card/expansion_tile_card.dart';
import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_overlay_loader/flutter_overlay_loader.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qianyi/controller/webSockerController.dart';
import 'package:qianyi/entity/recommend/VideoCircleEntity.dart';
import 'package:qianyi/network/http_manager.dart';
import 'package:qianyi/pages/home/community/page_view/like/mock.dart';
import 'package:qianyi/pages/home/community/page_view/widgets/publish_card.dart';
import 'package:qianyi/state/token.dart';
import 'package:qianyi/utils/throttle.dart';
import 'package:qianyi/view_model/Recommend/video_circle_model.dart';
import 'package:qianyi/view_model/home/recommend/recommend_data_model.dart';
import 'package:qianyi/wcao/kit/index.dart';
import 'package:qianyi/wcao/ui/tag.dart';
import 'package:qianyi/wcao/ui/theme.dart';
import 'package:dart_mock/dart_mock.dart' as mock;
import 'package:tap_to_expand/tap_to_expand.dart';

import '../../../../../controller/imageDetailVideoController.dart';
import '../../../../../entity/home/category_list_entity.dart';
import '../../../../../entity/home/recommend/Record.dart';
import '../../../../../network/http_config.dart';
import '../../../../../ui/watefall/pages/complex/known_sized_demo.dart';
import '../../../../../ui/watefall/pages/complex/variable_sized_demo.dart';
import '../../../../../ui/widget/custom_refresh.dart';
import '../../../../../view_model/home/recommend/recommend_category_view_model.dart';
import '../../../../../view_model/home/recommend/recommend_tag_view_model.dart';

/// HACK: 社区-推荐
class PageViewRecommend extends StatefulWidget
   {
  const PageViewRecommend({Key? key}) : super(key: key);

  @override
  State<PageViewRecommend> createState() => _PageViewRecommendState();
}

class _PageViewRecommendState extends State<PageViewRecommend>  with AutomaticKeepAliveClientMixin{
  final ScrollController scrollController = ScrollController();
  double opacity = 1;
  bool isScrollingUp = false; // 用于判断是否正在向上滑动
  double height = 0;
  bool isNoTag = true;
  String? tagId ;
  final PageStorageBucket _bucket = PageStorageBucket();
  WebSocketController webSocketController = Get.find();

  @override
  void initState() {


  }
  initDatas() {

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:

      KnownSizedDemo1(),
    )
      ;
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  Map<int, double> imagesHeightMap = {};

  double getRandomHeight(int index) {
    // 检查imagesHeightMap中是否已经存在对应索引的高度
    if (imagesHeightMap.containsKey(index)) {
      // 如果存在，返回该高度
      return imagesHeightMap[index]!;
    } else {
      // 如果不存在，生成一个新的随机高度并添加到Map中
      double height = Random().nextDouble() * (200 - 80) + 168;
      imagesHeightMap[index] = height;
      return height;
    }
  }

  buildWateFall1(RecommendTagViewModel viewModel, RecommendCategoryModel viewModel1) {
    ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();

    viewModel.datas;
    return  MasonryGridView.count(

      padding: EdgeInsets.all(2),
      // 展示几列
      crossAxisCount: 3,
      // 元素总个数
      itemCount: viewModel.datas.length,
      // 单个子元素
      itemBuilder: (BuildContext context, int index) {
        Record trendEntity = viewModel.datas[index];

        return GestureDetector(
          onTap: () async {
            imageDetailVideoController.imageDetailId.value = trendEntity.id!;
            await imageDetailVideoController.getImageVideoDetail();
            Get.toNamed("/ui/home/imageVideoDetail");

          },
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4.0),
            child:  Column(
              children: [

                FancyShimmerImage(
                  height: getRandomHeight(index),
                  imageUrl: trendEntity.cover!,
                ),
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                    overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                  ),

                )
                ,
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        ClipOval(
                            child: FancyShimmerImage(imageUrl: trendEntity.avatar as String,width: 20,height: 20,)
                        ),

                        Text(trendEntity.username as String),
                      ],
                    ),

                    Row(
                      children: [
                        Icon(
                          CupertinoIcons.heart,size: 14,),
                        Text(trendEntity.agreeCount as String)

                      ],
                    )
                  ],
                )
              ],
            ),
          ),
        );
      },

      // 纵向元素间距
      mainAxisSpacing: 5,
      // 横向元素间距
      crossAxisSpacing: 5,
      //本身不滚动，让外面的singlescrollview来滚动
      physics:const NeverScrollableScrollPhysics(),
      shrinkWrap: true, //收缩，让元素宽度自适应
    )


    ;


  }
  showLoading(BuildContext context) {
    Loader.show(context,
        isSafeAreaOverlay: false
        ,
        isBottomBarOverlay: false,

        overlayColor: Colors.black26,
        progressIndicator: SizedBox(
          width: 50,
          height: 50,
          child:  LoadingIndicator(
            indicatorType: Indicator.ballScaleMultiple, /// Required, The loading type of the widget
            colors:  [Colors.white,WcaoTheme.primary,WcaoTheme.primaryOpacity],       /// Optional, The color collections
            strokeWidth: 1,                     /// Optional, The stroke of the line, only applicable to widget which contains line

          ),
        ),
        themeData: Theme.of(context)
            .copyWith(colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Colors.green))
    );
  }
  buildWateFall(RecommendDataModel viewModel, RecommendCategoryModel viewModel1) {
    TokenController tokenController = Get.find();

    viewModel.datas;
    ImageDetailVideoController imageDetailVideoController = Get.find<ImageDetailVideoController>();

    return MasonryGridView.builder(

      padding: EdgeInsets.only(top: 0),
      gridDelegate: SliverSimpleGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3, // 展示几列
      ),
      itemCount: viewModel.datas.length, // 元素总个数
      itemBuilder: (BuildContext context, int index) {
        Record trendEntity = viewModel.datas[index];

        return GestureDetector(
          onTap: () async {
            HudUtil.showBeautiful(context);
            Map<String,dynamic> params = {
              "uid":tokenController.uid,
              "mid":trendEntity.id!
            };
            HttpManager.getInstance().request(url: "/platform/browseRecord/addBrowseRecord",params: params,method: Method.post);

            imageDetailVideoController.imageDetailId.value = trendEntity.id!;
            await imageDetailVideoController.getImageVideoDetail();
            // Loader.hide();
            HudUtil.dismiss();
            Get.toNamed("/ui/home/imageVideoDetail");

          },
          child: Card(
            margin: EdgeInsets.all(1.5),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(4.0),
              child:  Column(
                children: [
                  FancyShimmerImage(

                    height: getRandomHeight(index),
                    imageUrl: trendEntity.cover!,
                  )
                  ,


                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
                      overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
                    ),

                  )
                  ,
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          ClipOval(
                              child: FancyShimmerImage(imageUrl: trendEntity.avatar as String,width: 20,height: 20,)
                          ),

                          Text(trendEntity.username as String),
                        ],
                      ),

                      Row(
                        children: [
                          Icon(
                            CupertinoIcons.heart,size: 14,),
                          Text(trendEntity.agreeCount as String)

                        ],
                      )
                    ],
                  )
                ],
              ),
            ),
          ),
        );
      },
      mainAxisSpacing: 0, // 纵向元素间距
      crossAxisSpacing: 0, // 横向元素间距
      physics: const NeverScrollableScrollPhysics(), //本身不滚动，让外面的singlescrollview来滚动
      shrinkWrap: true, //收缩，让元素宽度自适应
    )

    // MasonryGridView.count(
    //
    //     padding: EdgeInsets.only(top: 0),
    //
    //   // 展示几列
    //   crossAxisCount: 3,
    //   // 元素总个数
    //   itemCount: viewModel.datas.length,
    //   // 单个子元素
    //   itemBuilder: (BuildContext context, int index) {
    //     Record trendEntity = viewModel.datas[index];
    //
    //     return  GestureDetector(
    //         onTap: () async {
    //           HudUtil.showBeautiful(context);
    //           Map<String,dynamic> params = {
    //             "uid":tokenController.uid,
    //             "mid":trendEntity.id!
    //           };
    //           HttpManager.getInstance().request(url: "/platform/browseRecord/addBrowseRecord",params: params,method: Method.post);
    //
    //           imageDetailVideoController.imageDetailId.value = trendEntity.id!;
    //           await imageDetailVideoController.getImageVideoDetail();
    //           // Loader.hide();
    //           HudUtil.dismiss();
    //           Get.toNamed("/ui/home/imageVideoDetail");
    //
    //         },
    //         child: Card(
    //           margin: EdgeInsets.all(1.5),
    //           child: ClipRRect(
    //             borderRadius: BorderRadius.circular(4.0),
    //             child:  Column(
    //               children: [
    //
    //                FancyShimmerImage(
    //                     height: getRandomHeight(),
    //                     imageUrl: trendEntity.cover!,
    //                   ),
    //
    //
    //                 Align(
    //                   alignment: Alignment.centerLeft,
    //                   child: Text(
    //                     trendEntity.content as String,maxLines: 2,softWrap: true, // 允许文本在超出最大行数时以省略号结束
    //                     overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.w400),// 设置文本左对齐
    //                   ),
    //
    //                 )
    //                 ,
    //                 Row(
    //                   mainAxisAlignment: MainAxisAlignment.spaceBetween,
    //                   children: [
    //                     Row(
    //                       children: [
    //                         ClipOval(
    //                             child: FancyShimmerImage(imageUrl: trendEntity.avatar as String,width: 20,height: 20,)
    //                         ),
    //
    //                         Text(trendEntity.username as String),
    //                       ],
    //                     ),
    //
    //                     Row(
    //                       children: [
    //                         Icon(
    //                           CupertinoIcons.heart,size: 14,),
    //                         Text(trendEntity.agreeCount as String)
    //
    //                       ],
    //                     )
    //                   ],
    //                 )
    //               ],
    //             ),
    //           ),
    //         ),
    //       )
    //     ;
    //   },
    //
    //   // 纵向元素间距
    //   mainAxisSpacing: 0,
    //   // 横向元素间距
    //   crossAxisSpacing: 0,
    //   //本身不滚动，让外面的singlescrollview来滚动
    //   physics:const NeverScrollableScrollPhysics(),
    //   shrinkWrap: true, //收缩，让元素宽度自适应
    // )


        ;


  }
}
